package com.wzz.config;


import com.alibaba.druid.support.json.JSONUtils;
import com.wzz.mapper.LoginLogMapper;
import com.wzz.pojo.LoginLog;
import com.wzz.utils.GetIPUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.session.StandardSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

//普通用户的后台拦截器
@Slf4j
@Component
public class HomeInterceptor implements HandlerInterceptor {

    @Autowired
    LoginLogMapper loginLogMapper;


    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //每一个项目对于登陆的实现逻辑都有所区别，我这里使用最简单的Session提取User来验证登陆。
//        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        //如果session中没有user，表示没登陆
        if (requestURI.endsWith("toLogin") ||
                requestURI.endsWith("login")) {

            return true;
        }
        if (requestURI.endsWith(".css") ||
                requestURI.endsWith(".js") ||
                requestURI.startsWith("/imgs")) {

            return true;
        }
//        if (requestURI.endsWith("favicon.ico")) {
//            return true;
//        }
        if (requestURI.endsWith(".mp3")) {
            return downLoadFile(request, response);
        }
        String ip = GetIPUtil.getIP(request);
        LoginLog data = loginLogMapper.selectByIp(ip);
        log.info("path {} 根据ip {} 查询登录信息 {} ", requestURI, ip, data);
        //(session.getAttribute("username") == null || session.getAttribute("userRole") == null)
        if (data == null) {
            //当前不满足条件,直接跳转拦截
            response.sendRedirect("/toLogin");
//            response.getWriter().println("need login");
            return false;
        } else {
            request.getSession().setAttribute("username",data.getUserName());
            request.getSession().setAttribute("userRole","2");
            return true;
        }

    }

    private boolean downLoadFile(HttpServletRequest request, HttpServletResponse response) {
        String[] split = request.getRequestURI().split("/");
        String fileName = split[split.length - 1];
        extracted(response, fileName);
        return false;
    }

    public static void extracted(HttpServletResponse response, String fileName) {
        File file = new File("/opt/data/voice/" + fileName);
        if (!file.exists()) {
            throw new RuntimeException("下载文件不存在");
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[4096];
            OutputStream os = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
            os.close();
        } catch (IOException e) {
            log.error("{}", e);
        }
    }

}
